/***
 * newsServices
 */
const NewsModel = require('../models/NewsModel')

const NewsServices = {
    add: async formData => {
        return NewsModel.create(formData)
    },
    edit: async editData => {
        if(!editData.newsid) {
            return Promise.reject('id未传，修改失败')
        }
        if(!await NewsModel.findOne({ newsid: editData.newsid})) {
            return Promise.reject('修改的数据不存在')
        }
        return NewsModel.updateOne({ newsid: editData.newsid }, editData)
    },
    query: async ({ title, page,limit, status }) => {
        let queryData = {}
        if(status) queryData.status = status
        const pattern = new RegExp(`.*${title}.*`, 'i');
        return NewsModel.find(title ?  { title: { $regex: pattern }, ...queryData } :{ ...queryData }).skip((page - 1) * limit).limit(limit)
    },
    queryOne: async newsid => {
        if(!newsid) {
           return Promise.reject('id未传，查询详情失败')
        }
        if(!await NewsModel.findOne({newsid})) {
            return Promise.reject('查询的数据不存在')
        }
        return NewsModel.findOne({newsid})
    },
    deleteOne: async newsid => {
      // 先判断当前数据是否是已发布，已发布状态的数据不允许删除
        if(!newsid) {
            return Promise.reject('id未传，删除失败')
        }
        const target = await NewsModel.findOne({newsid})
        if(!target) {
            return Promise.reject('删除的数据不存在')
        } else {
            if(target.status) {
                // 已经发布了
                return Promise.reject('当前数据已经发布，不可删除')
            } else {
                return NewsModel.deleteOne({ newsid })
            }
        }
    },
    queryCount: async ({ title }) => {
        const pattern = new RegExp(`.*${title}.*`, 'i');
        return NewsModel.countDocuments(title ?  { title: { $regex: pattern } } :{})
    }

}

module.exports = NewsServices
